package com.jackstraw.jack_base.util.exception.handler;


import com.jackstraw.jack_base.util.entity.response.ApiResponseBody;
import com.jackstraw.jack_base.util.entity.response.ResultBody;
import com.jackstraw.jack_base.util.entity.response.ResultInterfaceEnum;
import com.jackstraw.jack_base.util.exception.ExceptionUtil;
import com.jackstraw.jack_base.util.exception.BadRequestException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常全局处理
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    
    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BadRequestException.class)
    public ResultBody bizExceptionHandler(HttpServletRequest req, BadRequestException e) {
        log.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return ResultBody.error(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e) {
        log.error("发生空指针异常！原因是:", e);
        return ResultBody.error(ResultInterfaceEnum.BAD_REQUEST.getCode());
    }

    @ExceptionHandler({MethodArgumentTypeMismatchException.class})
    public ApiResponseBody<String> methodArgumentTypeMismatchException(
            MethodArgumentTypeMismatchException ex,
            HttpServletRequest request, HttpServletResponse response) {
        log.warn("MethodArgumentTypeMismatchException:", ex);
        StringBuilder msg = (new StringBuilder("参数：[")).append(ex.getName()).append("]的传入值：[")
                .append(ex.getValue()).append("]与预期的字段类型：[")
                .append(ex.getRequiredType().getName()).append("]不匹配");
        return this.handleException(400, "error.invalidParameter", msg.toString(), request,
                response);
    }

    /**
     * 处理 @vaild @null 异常
     *
     * @param ex
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Object methodArgumentNotValidException(MethodArgumentNotValidException ex,
                                                  HttpServletRequest request, HttpServletResponse response) {
        log.warn("MethodArgumentNotValidException:", ex);
        return this.handleException(400, "error.invalidParameter",
                ex.getBindingResult().getFieldError().getDefaultMessage(), request, response);
    }

    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResultBody exceptionHandler(HttpServletRequest req, Exception e) {
        log.error("未知异常！原因是:", e);
        return ResultBody.error(ResultInterfaceEnum.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
    }

    /**
     * 处理数据类型错误
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public ResultBody exceptionHandler1(HttpMessageNotReadableException ex, HttpServletRequest req, Exception e) {
        log.error("未知异常！原因是:", e);
        return ResultBody.error(ResultInterfaceEnum.INTERNAL_SERVER_ERROR.getCode(), "数据类型超过范围,请重新输入");
    }

    /**
     * handleException
     *
     * @param statusCode statusCode
     * @param errorKey   errorKey
     * @param msg        custom message
     * @param request    request
     * @param response   response
     * @return ApiResponseBody<T>
     * TODO statusCode 和 errorKey 可以合并
     */
    private ApiResponseBody<String> handleException(Integer statusCode, String errorKey,
                                                    String msg, HttpServletRequest request, HttpServletResponse response) {
        String errorCode = ExceptionUtil.getErrCode(errorKey);
        String errorMsg = ExceptionUtil.getErrMsg(errorKey);
        response.setStatus(statusCode);
        return new ApiResponseBody(errorCode,
                StringUtils.defaultIfEmpty(msg, errorMsg), "");
    }


}